package mq

import (
	"context"
	"strconv"
	"time"

	"github.com/lab-online/internal/report/entity"
	"github.com/lab-online/pkg/logger"
	"github.com/lab-online/pkg/mq"
	"github.com/rabbitmq/amqp091-go"
)

func (m *MQ) PublishReport(report entity.ReportEntity) error {
	ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
	defer cancel()
	if err := m.publishReportChannel.PublishWithContext(
		ctx,
		reportPublishExchange,
		getReportPublishRouterKey(report.GetID()),
		false,
		false,
		amqp091.Publishing{
			ContentEncoding: "utf-8",
			ContentType:     "application/json",
			Body:            []byte(report.GetContent()),
		},
	); err != nil {
		logger.Error("Failed to publish report", err.Error())
		return mq.ErrPublish
	}

	return nil
}

func getReportPublishRouterKey(reportID uint) string {
	return "report." + strconv.FormatUint(uint64(reportID), 10)
}
